--[[
    基本需求分析：

在进入游戏的时候创建一个稻草人
出来
然后在被打死以后会复活
玩家会加分并且显示出来   
]]


--[[
DEBUG_SIGNAL = true--判断代码是否处于调试状态
Game_Start = function()
    local ret = nil
    local x,y,z
    local objids
    ret, x, y, z = Player:getPosition(playerId)
    if ret == ErrorCode.OK then
        ret, objids = World:spawnCreature(x, y, z, 3121, 1)
        if ret == ErrorCode.OK then
            Chat:sendChat('创建生物失败', 0)
        else
            Chat:sendChat('生物生成成功', 0)
        end
    else
        Chat:sendChat('获取玩家坐标失败', 0) 
    end
end
Player_Score = function(trigger_obj)
--注册事件机制
ScriptSupportEvent:registerEvent([=[Game.Start]=], Game_Start)
ScriptSupportEvent:registerEvent([=[Actor.Die]=], Player_Score)
]]



--[[$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
----2020年2月7日12:10:02 用户进入游戏以后进行提示 
function Error_Handle(func)
    local status, err = pcall(func)
    if not status then
        Chat:sendSystemMsg('脚本错误：'..err, 0)
    end
end

Error_Handle(function ()
--程序的开头

DEBUG = true           --故意的错误 ==
Cur_Id = nil
--IsGETUserInput = false  --是否读取用户输入 缩写成IGUI
main_page_IGUI = false
set_pwd_IGUI  = false --pwd password密码的缩写
User_Data = {}
User_Data[0] = {['Account']='742460495',['Password']='170305'}
User_Data[1] = {['Account']='742460491',['Password']='420315'}



AnyPlayer_EnterGame = function(trigger_obj)
    local PlayerId = trigger_obj['eventobjid']
    if DEBUG == true then
        --local DebugId = trigger_obj['toobjid']           
            --Chat:sendSystemMsg('eventobjid'.. tostring(PlayerId) ,PlayerId)
            Chat:sendChat('eventobjid'.. tostring(PlayerId) ,PlayerId)
            --Chat:sendSystemMsg('toobjid'.. tostring(trigger_obj['toobjid']) ,PlayerId)
    end
    local User_Msg  = '如果你是第一次进入这款游戏，请你点击鼠标右键阅读信纸里面的说明信息'
    Game:msgBox(User_Msg)
    --Chat:sendChat(User_Msg , PlayerId)
    --用户操作菜单
    User_Msg = '在对话框中输入不同的指令(在对应的指令前加上/,例如/a),然后摁回车代表你接下来想要执行的操作'
    local User_Menu = '1.如果你已经成功注册账号密码，输入L进行登录2.如果你没有注册，输入R进行注册3.如果你想退出游戏，输入E进行退出'
    Chat:sendSystemMsg(User_Msg,PlayerId)
    --Game:msgBox(User_Menu)
    --Player:notifyGameInfo2Self(PlayerId, User_Menu)
    Chat:sendSystemMsg(User_Menu,PlayerId)
    --Chat:sendChat('-------------------------------------',PlayerId)
    --清空缓冲区，干扰字符串扫描操作
    main_page_IGUI = true
end


--针对用户输入的指令
Player_Input = function(event_args)
    if main_page_IGUI == true then
        local Instruction = event_args['content']
        Cur_Id = event_args['eventobjid']
        if DEBUG == true then
            --Chat:sendChat(Instruction,event_args['eventobjid'])
            -- body
        end
        --string.upper(Instruction)
        if string.find (Instruction, '/L', 1) ~= nil then
            --Chat:sendChat(string.find (Instruction, 'L', 2),event_args['eventobjid'])
            Chat:sendChat('执行登录操作',event_args['eventobjid'])--login函数
            main_page_IGUI = false
        elseif string.find (Instruction, '/R', 1) ~= nil then
            Chat:sendChat('执行注册操作',event_args['eventobjid'])            
            main_page_IGUI = false
            User_Register()
        elseif string.find (Instruction, '/E', 1) ~= nil then
            --local result = World:despawnActor(event_args['eventobjid'])
            --if result == ErrorCode.OK then print('Despawn the last actor') end
            --main_page_IGUI = false
        end
        
    end
end

function User_Login( ... )
    -- body

end

function User_Register()
    local i,ID_String    --当前player的迷你号
    local has_Register = false
    ID_String = tostring(Cur_Id)
    --Cur_Id = event_args['eventobjid']
    for i=1,table.length(User_Data) do
        if string.find(User_Data[i].Account,ID_String) ~= nil then
            has_Register = true           
            Game:msgBox('你的账号已经注册过了，无需多次注册，请自行退出游戏后重新进入然后选择登录界面')
            break        
        end      
    end
    if has_Register == false then
        Chat:sendChat('设置你的密码（账号为你的迷你号，无需设置）',Cur_Id)
        set_pwd_IGUI = true
    end
end

Set_Password = function(event_args)
    if set_pwd_IGUI = true then




----下面是保证程序是能够正常工作的函数，还有一些工具性的函数
--保证事件机制正常工作
Player_MoveStep = function(event_args)
	local playerId = event_args['eventobjid']
	local ret, x, y, z = Player:getPosition()

	local ret, curdir = Player:getCurPlaceDir(playerId)
	if curdir == FACE_DIRECTION.DIR_NEG_X then x = x+2; z = z+2 end
	if curdir == FACE_DIRECTION.DIR_POS_X then x = x-2; z = z-2 end
	if curdir == FACE_DIRECTION.DIR_NEG_Z then z = z+2; x = x+2 end
	if curdir == FACE_DIRECTION.DIR_POS_Z then z = z-2; x = x-2 end
	Block:replaceBlock(104, x, y, z)
end

 
Game_Started = function()   

end



function Grammatical_Error()
    -- if DEBUG_SIGNAL == true then
    --     Chat:sendChat('Grammatical correctness', 0)--如果代码处于调试阶段没有这句话，说明存在语法错误
    -- end
    Chat:sendChat('Grammatical correctness', 0)
    --注意：语法错误可能存在于这段代码自身之中
end

function table.length(t)
    local i = 0
    for k, v in pairs(t) do
        i = i + 1
    end
    return i
end

Grammatical_Error()--在语法正确的时候执行


ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], AnyPlayer_EnterGame)
ScriptSupportEvent:registerEvent([=[Player.MoveOneBlockSize]=], Player_MoveStep)
ScriptSupportEvent:registerEvent([=[Game.Start]=], Game_Started)
ScriptSupportEvent:registerEvent([=[Player.InputContent]=], Player_Input)
ScriptSupportEvent:registerEvent([=[Player.InputContent]=], Set_Password)

    -- 内容
end)
------------------代码模块分界线----------------
----$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$]]


    -- local ret1,second1 = MiniTimer:getTimerTime(Memory_Update_TimerID)
    -- -- if ret ~= ErrorCode.OK then
    -- --     Chat:sendChat('(Alert)second:'..tostring(second), 0)
    -- -- end
    -- local ret2,second2 = MiniTimer:getTimerTime(User_Alive_TimerID)
    -- if second1 == 30 then 
    --     local i
    --     for i=1,table.length(User_Data) do
    --         if User_Data[i].Alive == true then
    --             User_Data[i].Time =  User_Data[i].Time - 10
    --             --Chat:sendChat('timeleft:'..tostring(User_Data[i].Time), 0)
    --         end
    --     end
    --     --timeleft = timeleft - 5
    --     --before_second = second
    --     --Chat:sendChat('second:'..tostring(second), 0)
    --     --
    -- end 
    -- if second2 == 2 then 
    --     local Player_Alive,value,i
    --     for i=1,table.length(User_Data) do
    --         Player_Alive,value =  Player:getAttr(tonumber(User_Data[i].Account), PLAYERATTR.CUR_HP)
    --         if Player_Alive ~= ErrorCode.OK then
    --             User_Data[i].Alive = fals
    --         end
    --     end
    --     --timeleft = timeleft - 5
    --     --before_second = second
    --     --Chat:sendChat('second:'..tostring(second), 0)
    --     --
    -- end 
    -- MiniTimer:startBackwardTimer(Memory_Update_TimerID)
    -- MiniTimer:startBackwardTimer(User_Alive_TimerID)
-- other_player_entergame = function()
--     local playerId = event_args['eventobjid']
--     local count = 0
--     while(1)
--     do
--         if count > 50000000 then
--             Chat:sendSystemMsg('陷入死循环，强制退出',0) 
--             Chat:sendSystemMsg('数据库状态：'..tostring(is_database_load))
--             break
--         end

--        if is_database_load == true then
--             Chat:sendSystemMsg('process2')
--             local has_Register,old_player = is_new_player(playerId)
--             if has_Register == false then
--                 Chat:sendSystemMsg('欢迎新玩家'..tostring(playerId),0)  
--                 --将玩家的信息加入数据库之中
--                 Chat:sendSystemMsg('阅读信纸道具里面的内容',playerId)
--                 register_new_player(playerId)
--                 prepare_player_game(playerId)
--             else
--                 Chat:sendSystemMsg('欢迎老玩家'..tostring(playerId),0) 
--                 User_Data[old_player].Alive = true
--                 move_player_in_waiting_area(old_player) 
--                 prepare_player_game(playerId)  
--                 --如果不用移的话，就移入游戏区域
--             end
--             break
--         end
--         count = count + 1
--     end
--     if count > 5000 then
--         Chat:sendSystemMsg('死循环退出'..tostring(playerId),0) 
--     else
--         Chat:sendSystemMsg('分流后退出退出'..tostring(playerId),0) 
--     end  
-- end


--2020年2月7日18:51:06 业务逻辑重写

--用户在内存中的数据
User_Data = {}
--User_Data[0] = {['Account']='742460495',['Time']=999,['Alive']=false}
--User_Data[1] = {['Account']='742460495',['Time']=199,['Alive']=false}
--User_Data[2] = {['Account']='742445321',['Time']=999,['Alive']=false}

--TimerID  = nil
--second = nil
--User_Alive_TimerID = nil
-- local playPos = {x=cxPos-1, y=Y+1, z=czPos-1}
-- Block:setBlockAll(playPos.x, playPos.y, playPos.z, cellId)
-- PlayerPos[#PlayerPos+1] = playPos --这个出生点都是现场计算出来的

--用户的出生点
spawn_point = {}
spawn_point[0] = {x=0,y=11,z=6}
spawn_point[1] = {x=-5,y=11,z=-22}
--local isGRuleInit = false --规则是否已设置 没有用处

--等待区域
wait_point = {x=10,y=7,z=-23}

--数据库的相关信息
database_info = {}
database_info['begin_point'] = {x = -4,y = 9,z = -5}--数据库从哪里开始读取
is_database_load = false


--根据内存信息建造数据库
function encode_database()
    --database_info['begin_point'] = {x = -25,y = 9,z = -5}--数据库从哪里开始创建
    --database_info['begin_point'] = {x = -25,y = 9,z = 5}    
    database_info['begin_point'] = {x = -27,y = 8,z = -12}
    local attribute_index = -1 --,attribute_num -- 按照数值方式储存起来的属性
    local record_index = 0
    local i = nil
    -- User_Data[2] = {['Account']='341894728',['Time']=1794,['Alive']=true}
    --Chat:sendSystemMsg('table.length(User_Data)'..table.length(User_Data))
    --Chat:sendSystemMsg('User_Data[0]'..tostring(User_Data[0].Account))
    --Chat:sendSystemMsg('User_Data[1]'..tostring(User_Data[1].Account))
    --Chat:sendSystemMsg('User_Data[2]'..tostring(User_Data[2].Account))
    for i=1,table.length(User_Data) do --转换完一条转下一条
        --编码一条记录
        attribute_index = encode__attribute(attribute_index,record_index,1)
        attribute_index = encode__attribute(attribute_index,record_index,2)
        attribute_index = encode__attribute(attribute_index,record_index,3)
        attribute_index,record_index = encode_another_record(attribute_index,record_index)
    end
    end_of_encoding(attribute_index,record_index)
end

function end_of_encoding(attribute_index,record_index)
    local i = attribute_index + 1
    local j = record_index  
    Block:placeBlock(612, 
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j, 4)  
end

function encode_another_record(attribute_index,record_index)
    local i = attribute_index + 1
    local j = record_index
    Block:placeBlock(611, 
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j, 4)   
    i = -1
    j = j + 1
    return i,j
end

function encode__attribute(attribute_index,record_index,option)
    local i = attribute_index + 1
    local j = record_index
    local block_id = nil
    local attribute_num_table = nil
    if option == 1 then
        attribute_num_table = analyse_number(tonumber(User_Data[record_index + 1].Account))
    elseif option == 2 then
        attribute_num_table = analyse_number(User_Data[record_index + 1].Time)
    elseif option == 3 then 
        if User_Data[record_index + 1].Alive  == true then
            attribute_num_table = analyse_number(2)
        else
            attribute_num_table = analyse_number(1) --不能很好的分析0这个数据 1表示false 2表示true
        end
    else
        Chat:sendSystemMsg('the option is not supported.')
    end
    local k = table.length(attribute_num_table)
    --,['Time']=999,['Alive']=false}
    -- Chat:sendSystemMsg('block_id:'..tostring(block_id))
    -- Chat:sendSystemMsg('attribute_num_table[9]:'..tostring(attribute_num_table[9]))
    -- Chat:sendSystemMsg('attribute_num_table[0]):'..tostring(attribute_num_table[0]))
    while( k > 0)
    do
        block_id = attribute_num_table[k] + 600
        -- if(k > 5) then
        --     Chat:sendSystemMsg('block_id:'..tostring(block_id))
        -- end
        Block:placeBlock(block_id, 
            database_info['begin_point'].x-i, 
            database_info['begin_point'].y, 
            database_info['begin_point'].z+j, 4)
        k = k - 1
        i = i + 1
    end
    Block:placeBlock(610, 
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j, 4)
    return i
end

function analyse_number(number)
    local position = {}
    local position_value = nil
    local sum = 0
    local time = 1
    while(number ~= 0)
    do
        position_value = number % 10
        table.insert(position,position_value)
        sum = sum + position_value*time
        time = time*10
        number = math.floor(number / 10)
    end  
    --Chat:sendSystemMsg('sum:'..tostring(sum))
    return position
end

--把数据库内的信息转化到内存上
function decode_database() 
    --database_info['begin_point'] = {x = -25,y = 9,z = -5} --改变数据库的原点，我们已经拥有这个操作了
    --database_info['begin_point'] = {x = -25,y = 9,z = -5}
    database_info['begin_point'] = {x = -27,y = 8,z = -12}
    local attribute_index = -1
    local attribute_num  -- 按照数值方式储存起来的属性
    local record_index = 0
    local is_end = end_of_database(attribute_index,record_index)
    local current_record_table = {}
    local finish_exe = false
    while(is_end ~= true)
    do
        attribute_num,attribute_index  = decode_attribute(attribute_index,record_index)
        --Chat:sendSystemMsg('account:'..tostring(attribute_num)) --还要写转内存的操作
        current_record_table.Account = tostring(attribute_num)

        attribute_num,attribute_index  = decode_attribute(attribute_index,record_index)
        --Chat:sendSystemMsg('time_left:'..tostring(attribute_num)) 
        current_record_table.Time = attribute_num

        attribute_num,attribute_index = decode_attribute(attribute_index,record_index)
        if attribute_num == 1 then
            current_record_table.Alive = false
        else
            current_record_table.Alive = true
        end
        --Chat:sendSystemMsg('alive:'..tostring(attribute_num))  

        attribute_index,record_index = begin_new_record(attribute_index,record_index)

        table.insert(User_Data,ref_table(current_record_table))

        is_end = end_of_database(attribute_index,record_index)

        if is_end == true then
            --Chat:sendSystemMsg('end_of_database') 
        else
            --Chat:sendSystemMsg('there is record') 
        end       
    end
    finish_exe = true
    return finish_exe
    -- if end_of_database(attribute_index,record_index) == true then
    --     Chat:sendSystemMsg('end_of_database') 
    -- else
    --     Chat:sendSystemMsg('there is record') 
    --end
end

function decode_attribute(attribute_index,record_index)
    local i = attribute_index + 1 --控制行
    local j = record_index --控制列
    local sum = 0
    ret,block_id = Block:getBlockID(database_info['begin_point'].x-i, database_info['begin_point'].y, database_info['begin_point'].z+j)
    while(block_id < 610)
    do
       --process id
        sum = sum*10 +(block_id - 600) --将各个位的数据组合成一个大数据
        i = i + 1 --写成死循环了，环境直接奔溃了
        ret,block_id = Block:getBlockID(database_info['begin_point'].x-i, database_info['begin_point'].y, database_info['begin_point'].z+j)    
    end 
    return sum,i--函数结束，返回计算出来的结果和单个属性的结尾，就是标志位的坐标
end

function begin_new_record(attribute_index,record_index)
    local i = attribute_index + 1 --看看最后一个方块的情况
    local j = record_index
    local ret,block_id = Block:getBlockID(database_info['begin_point'].x-i, database_info['begin_point'].y, database_info['begin_point'].z+j)
    if block_id == 611 then
        j = j + 1 --下一条记录的坐标，是Z轴上加1
        i = -1
        return i,j
    end
end

function end_of_database(attribute_index,record_index)
    local i = attribute_index + 1--因为attribute_index设置的是-1，所以要加1，才能读到正确的位置
    local j = record_index
    local ret,block_id = Block:getBlockID(database_info['begin_point'].x-i, database_info['begin_point'].y, database_info['begin_point'].z+j)
    if block_id == 612 then
        return true
    else 
        return false
    end
end

function ref_table(table)
    local ref_table = {}
    ref_table.Account = table.Account
    ref_table.Time = table.Time
    ref_table.Alive = table.Alive
    return ref_table
end

--销毁给定坐标原点的数据库
function wipe_out_database() 
    --database_info['begin_point'] = {x = -25,y = 9,z = -5} --改变数据库的原点，我们已经拥有这个操作了
    --database_info['begin_point'] = {x = -25,y = 9,z = -5}
    --database_info['begin_point'] = {x = -25,y = 9,z = -5}
    --database_info['begin_point'] = {x = -25,y = 9,z = 5}
    database_info['begin_point'] = {x = -27,y = 8,z = -12}
    --Chat:sendSystemMsg('database_info:'..tostring(database_info['begin_point'].x))
    --database_info['begin_point'] = {x = -25,y = 9,z = -5}--数据库从哪里开始创建
    local attribute_index = -1
    local attribute_num  -- 按照数值方式储存起来的属性
    local record_index = 0
    local is_end = last_of_database(attribute_index,record_index)
    --local current_record_table = {}
    while(is_end ~= true)
    do
        attribute_num,attribute_index  = destory_attribute(attribute_index,record_index)
        --Chat:sendSystemMsg('account:'..tostring(attribute_num)) --还要写转内存的操作
        --current_record_table.Account = tostring(attribute_num)

        attribute_num,attribute_index  = destory_attribute(attribute_index,record_index)
        --Chat:sendSystemMsg('time_left:'..tostring(attribute_num)) 
        --current_record_table.Time = attribute_num

        attribute_num,attribute_index = destory_attribute(attribute_index,record_index)
        -- if attribute_num == 1 then
        --     current_record_table.Alive = false
        -- else
        --     current_record_table.Alive = true
        -- end
        --Chat:sendSystemMsg('alive:'..tostring(attribute_num))  

        attribute_index,record_index = destory_new_record(attribute_index,record_index)

        --table.insert(User_Data,ref_table(current_record_table))

        is_end = final_of_database(attribute_index,record_index)

        if is_end == true then
            Chat:sendSystemMsg('end_of_database') 
        else
            Chat:sendSystemMsg('there is record') 
        end       
    end

    -- if end_of_database(attribute_index,record_index) == true then
    --     Chat:sendSystemMsg('end_of_database') 
    -- else
    --     Chat:sendSystemMsg('there is record') 
    --end
end

function last_of_database(attribute_index,record_index)
    local i = attribute_index + 1--因为attribute_index设置的是-1，所以要加1，才能读到正确的位置
    local j = record_index
    local ret,block_id = Block:getBlockID(
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j)
    Block:destroyBlock(
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j)
    if block_id == 612 then
        return true
    else 
        return false
    end
end

function final_of_database(attribute_index,record_index)
    local i = attribute_index + 1--因为attribute_index设置的是-1，所以要加1，才能读到正确的位置
    local j = record_index
    local ret,block_id = Block:getBlockID(
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j)
        Block:destroyBlock(
            database_info['begin_point'].x-i, 
            database_info['begin_point'].y, 
            database_info['begin_point'].z+j)
    if block_id == 612 then
        return true
    else 
        return false
    end
end

function destory_new_record(attribute_index,record_index)
    local i = attribute_index + 1 --看看最后一个方块的情况
    local j = record_index
    local ret,block_id = Block:getBlockID(
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j)
        Block:destroyBlock(
            database_info['begin_point'].x-i, 
            database_info['begin_point'].y, 
            database_info['begin_point'].z+j)
    if block_id == 611 then
        j = j + 1 --下一条记录的坐标，是Z轴上加1
        i = -1
        return i,j
    end
end

function destory_attribute(attribute_index,record_index)
    local i = attribute_index + 1 --控制行
    local j = record_index --控制列
    local sum = 0
    ret,block_id = Block:getBlockID(database_info['begin_point'].x-i, database_info['begin_point'].y, database_info['begin_point'].z+j)
    Block:destroyBlock(
        database_info['begin_point'].x-i, 
        database_info['begin_point'].y, 
        database_info['begin_point'].z+j) 
    while(block_id < 610)
    do
       --process id
        sum = sum*10 +(block_id - 600) --将各个位的数据组合成一个大数据
        i = i + 1 --写成死循环了，环境直接奔溃了
        ret,block_id = Block:getBlockID(
            database_info['begin_point'].x-i, 
            database_info['begin_point'].y, 
            database_info['begin_point'].z+j)
        Block:destroyBlock(
            database_info['begin_point'].x-i, 
            database_info['begin_point'].y, 
            database_info['begin_point'].z+j)  
    end 
    return sum,i--函数结束，返回计算出来的结果和单个属性的结尾，就是标志位的坐标
end


--周期性的移除余额不足的玩家
function Kick_Out_Player(secs,period)
    if math.fmod(secs, period) == 0 then 
        local i
        for i=1,table.length(User_Data) do
            move_player_in_waiting_area(i)             
        end
    end 
end

--把余额不足的玩家移入等待区域
function move_player_in_waiting_area(index)
    if User_Data[index].Time < 10 and User_Data[index].Alive == true then
        Player:setPosition(tonumber(User_Data[index].Account), wait_point.x, wait_point.y, wait_point.z)
        --Chat:sendSystemMsg(User_Data[index-1].Account..'时间不足')
        Chat:sendSystemMsg('尊敬的玩家，您剩余的在线游戏时间已经不足，现将您移入等待区域，请及时联系客服人员进行充值，在充值完成以后就可以离开等待区域',tonumber(User_Data[index-1].Account))       
    end   
end

--减少玩家允许的在线时间
function Cut_Down_Time(secs,period)  
    if math.fmod(secs, period) == 0 then 
        local i
        for i=1,table.length(User_Data) do
            if User_Data[i].Alive == true and User_Data[i].Time >= 10 then
                User_Data[i].Time =  User_Data[i].Time - period                 
            end  
            --Chat:sendSystemMsg('Account:'..User_Data[i].Account..' timeleft:'..tostring(User_Data[i].Time), 0)                            
        end
    end 
end

--检查玩家是否在线
function Check_Player_Alive(secs,period)
    if math.fmod(secs, period) == 0 then 
        local i
        for i=1,table.length(User_Data) do
            local Player_Alive,value = Player:getAttr(tonumber(User_Data[i].Account), PLAYERATTR.CUR_HP)--能够识别离线玩家
            if Player_Alive ~= ErrorCode.OK then
                User_Data[i].Alive = false
                --Chat:sendChat('check-running', 0) 
            end
            --Chat:sendChat('Account:'..User_Data[i].Account..'  Alive:'..tostring(User_Data[i].Alive), 0)
        end
    end
end

function persist_user_data(secs,period)
    if math.fmod(secs, period) == 0 then 
        Chat:sendChat('function enter', 0) 
        wipe_out_database() 
        Chat:sendChat('wipe_out_database', 0) 
        encode_database()
        Chat:sendChat('encode_database', 0) 
    end
end


--将新玩家的信息加入数据库中
function register_new_player(playerId)
    local USER_INIT_DATA = {}
    USER_INIT_DATA['Account'] = tostring(playerId)
    USER_INIT_DATA['Time'] = 60
    USER_INIT_DATA['Alive'] = true
    table.insert(User_Data,USER_INIT_DATA)
end

--判断进入游戏的是不是新玩家
function is_new_player(playerId)
    local i 
    local old_player = nil
    local has_Register = false
    -- if is_database_load == false then
    --     Chat:sendSystemMsg('is_database_ NOT_load')
    -- end
    for i=1,table.length(User_Data) do
        if string.find(User_Data[i].Account,tostring(playerId)) ~= nil then
            has_Register = true  
            old_player = i      
            break        
        end      
    end
    return has_Register,old_player
end


--设置玩家所属的队伍
function assign_player_team(playerId)
    local player_count = table.length(User_Data)
    --Chat:sendSystemMsg('debug:player_count ')
    if math.mod(player_count , 2) == 1 then--单数红队
        --Chat:sendSystemMsg('debug:红队  ')
        --Team:changePlayerTeam(playerid, 1)
        Player:setTeam(playerId, 1)
    else --双数蓝队
        --Chat:sendSystemMsg('debug:蓝队 ')
        --Team:changePlayerTeam(playerid, 2)
        Player:setTeam(playerId, 2)
    end
    --Chat:sendSystemMsg('debug:setTeam ')
end

--给玩家分配初始化的状态
function equip_players(playerId)
    Player:gainItems(playerId, 4097, 1, 1)
    --给玩家装备标准步枪，1把
end

--根据玩家所处的队伍，分配不同的复活点
function send_player_into_battlefield(playerId)
    local ret,flag = Player:getTeam(playerId) --根据玩家所处的队伍进行指派
    Chat:sendSystemMsg('flag:'..tostring(flag))
    if  flag == 1 then
        Actor:setPosition(playerId, spawn_point[0].x, spawn_point[0].y, spawn_point[0].z)
        --Player:setPosition(playerId, spawn_point[0].x, spawn_point[0].y, spawn_point[0].z)
    else --出生点的位置之前在编辑模式中已经指定了
        Actor:setPosition(playerId, spawn_point[1].x, spawn_point[1].y, spawn_point[1].z)
        --Player:setPosition(playerId, spawn_point[1].x, spawn_point[1].y, spawn_point[1].z)
    end
end

function prepare_player_game(playerId)
    Chat:sendSystemMsg('playerId:'..tostring(playerId))
    Chat:sendSystemMsg('debug:function_enter')
    assign_player_team(playerId)
    Chat:sendSystemMsg('debug:assign_player_team')
    send_player_into_battlefield(playerId)
    Chat:sendSystemMsg('debug:send_player_into_battlefield')
    equip_players(playerId)
    Chat:sendSystemMsg('debug:equip_players')
end

function add_more_time(admin_id,admin_str)
    if admin_id == 742460495 then --只有预先设定好的玩家有权限
        local i
        for i=1,table.length(User_Data) do
            if string.find(User_Data[i].Account,admin_str) ~= nil then
                User_Data[i].Time = User_Data[i].Time + 3600
                Chat:sendSystemMsg('玩家：'..User_Data[i].Account..'增加一小时的游玩时间，如果之前处于等待区域，那么您可以离开等待区域了',0)  
                break        
            end      
        end
    end
end

is_done_before = false
--将进入游戏的玩家进行分流
mainPlayer_EnterGame = function()
    --local playerId = event_args['eventobjid']
    if  is_done_before == false then
        local ret,playerId = Player:getHostUin()
        --Chat:sendSystemMsg('playerId：'..tostring(playerId))
        if playerId == 742460495 then
            local i
            is_database_load = decode_database()
            Chat:sendSystemMsg('数据库状态：'..tostring(is_database_load))
            for i=1,table.length(User_Data) do
                Chat:sendSystemMsg('Account：'..tostring(User_Data[i].Account))
            end
        else
            Chat:sendSystemMsg('playerId：'..tostring(playerId == 742460495))
        end
        Chat:sendSystemMsg('process1')
        local count = 0
        while(1)
        do
            if count > 50000000 then
                Chat:sendSystemMsg('陷入死循环，强制退出',0) 
                Chat:sendSystemMsg('数据库状态：'..tostring(is_database_load))
                break
            end
    
           if is_database_load == true then
                Chat:sendSystemMsg('process2')
                local has_Register,old_player = is_new_player(playerId)
                if has_Register == false then
                    Chat:sendSystemMsg('欢迎新玩家'..tostring(playerId),0)  
                    --将玩家的信息加入数据库之中
                    Chat:sendSystemMsg('阅读信纸道具里面的内容',playerId)
                    register_new_player(playerId)
                    prepare_player_game(playerId)
                else
                    Chat:sendSystemMsg('欢迎老玩家'..tostring(playerId),0) 
                    User_Data[old_player].Alive = true
                    move_player_in_waiting_area(old_player) 
                    prepare_player_game(playerId)  
                    --如果不用移的话，就移入游戏区域
                end
                break
            end
            count = count + 1
        end
        if count > 5000 then
            Chat:sendSystemMsg('死循环退出'..tostring(playerId),0) 
        else
            Chat:sendSystemMsg('分流后退出退出'..tostring(playerId),0) 
        end
        is_done_before = true
    end 
end


--测试事件机制和语法错误，在现在的版本中已经被禁用
Player_MoveStep = function(event_args)
	local playerId = event_args['eventobjid']
	local ret, x, y, z = Player:getPosition()
	local ret, curdir = Player:getCurPlaceDir(playerId)
	if curdir == FACE_DIRECTION.DIR_NEG_X then x = x+2; z = z+2 end
	if curdir == FACE_DIRECTION.DIR_POS_X then x = x-2; z = z-2 end
	if curdir == FACE_DIRECTION.DIR_NEG_Z then z = z+2; x = x+2 end
	if curdir == FACE_DIRECTION.DIR_POS_Z then z = z-2; x = x-2 end
	Block:replaceBlock(104, x, y, z)
end

--管理员的特权指令，输入以后增加玩家游戏时间
admin_state = function(event_args)
    local admin_id = event_args['eventobjid']
    local admin_str = event_args['content']
    add_more_time(admin_id,admin_str)
end

--玩家复活以后，要送入队伍的出生点，并且给予装备
Player_Revive = function(event_args)
    --防止在等待区域的玩家在击杀对方以后复活进入游戏，其实进入以后
    --还是会被系统拉会原地，反正这个功能就是好
    local playerId = event_args['eventobjid']
    --添加复活保护buff
    --prepare_player_game(playerId)
    --Chat:sendSystemMsg('debug:assign_player_team')
    send_player_into_battlefield(playerId)
    --Chat:sendSystemMsg('debug:send_player_into_battlefield')
    equip_players(playerId)
    --Chat:sendSystemMsg('debug:equip_players')
end

--在游戏开始时创建计时器
Game_Start = function()
	local ret, timerId = MiniTimer:createTimer("计时X")
	if ret == ErrorCode.OK then --启动计时器
        MiniTimer:startForwardTimer(timerId)
        Chat:sendSystemMsg('开始计时')
    end
    -- is_database_load = decode_database()
    -- Chat:sendSystemMsg('数据库状态：'..tostring(is_database_load))
    -- for i=1,table.length(User_Data) do
    --     Chat:sendSystemMsg('Account：'..tostring(User_Data[i].Account))
    -- end
end

-- init_user_data = function(event_args)
--     local i
--     local player_id = event_args['eventobjid']
--     if  player_id == 742460495  then
--         is_database_load = decode_database()

--     end
--     Chat:sendSystemMsg('数据库状态：'..tostring(is_database_load))
--     for i=1,table.length(User_Data) do
--         Chat:sendSystemMsg('Account：'..tostring(User_Data[i].Account))
--     end
    
-- end

--根据计时器的时间周期，定期调整玩家的状态
Timer_Change = function(event_args)
	local timerid = event_args['timerid']
    local ret, secs = MiniTimer:getTimerTime(timerid)
     if ret == ErrorCode.OK and is_database_load == true then
    --if ret == ErrorCode.OK then
        Check_Player_Alive(secs,2)
        Cut_Down_Time(secs,5)      
        Kick_Out_Player(secs,10)
        persist_user_data(secs,10)
	end
end


--工具函数
function Grammatical_Error()
    -- if DEBUG_SIGNAL == true then
    --     Chat:sendChat('Grammatical correctness', 0)--如果代码处于调试阶段没有这句话，说明存在语法错误
    -- end
    Chat:sendChat('Grammatical correctness', 0)
    --注意：语法错误可能存在于这段代码自身之中
end

function table.length(t)
    local i = 0
    for k, v in pairs(t) do
        i = i + 1
    end
    return i
end

Grammatical_Error()--在语法正确的时候执行

construct_database = function(event_args)
    local player_id = event_args['eventobjid']
    if player_id == 742460495 then
        --decode_database()
        --is_database_load = true
        Chat:sendSystemMsg('开始事件机制')
        encode_database()
        --非系统管理员进入游戏时，不加载数据库的信息
    end
end

begin_game = function(event_args)
    local player_id = event_args['eventobjid']
    local block_id = event_args['blockid']
    if player_id == 742460495 then
        if block_id == 614 then
            --Chat:sendSystemMsg('执行指令'..tostring(playerId),0) 
            is_database_load = decode_database()
            Chat:sendSystemMsg('游戏加载完成') 
        end 
    end
end

any_enter_game = function(event_args)
    local playerId = event_args['eventobjid']
    local block_id = event_args['blockid']
    if is_database_load == true then
        --Chat:sendSystemMsg('process2')
        if  block_id == 615 then
            local has_Register,old_player = is_new_player(playerId)
            if has_Register == false then
                Chat:sendSystemMsg('欢迎新玩家'..tostring(playerId),0)  
                --将玩家的信息加入数据库之中
                Chat:sendSystemMsg('阅读信纸道具里面的内容',playerId)
                register_new_player(playerId)
                prepare_player_game(playerId)
            else
                Chat:sendSystemMsg('欢迎老玩家'..tostring(playerId),0) 
                User_Data[old_player].Alive = true
                move_player_in_waiting_area(old_player) 
                prepare_player_game(playerId)  
                --如果不用移的话，就移入游戏区域
            end
        end
    else
        Chat:sendSystemMsg('数据库未装载:'..tostring(playerId),0)
    end
end
--ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], construct_database)
--为了测试停用的代码
--ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], AnyPlayer_EnterGame)
--ScriptSupportEvent:registerEvent([=[Player.Init]=], AnyPlayer_EnterGame)
--ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], init_user_data)

ScriptSupportEvent:registerEvent([=[Game.Start]=], Game_Start)
ScriptSupportEvent:registerEvent([=[minitimer.change]=], Timer_Change)
ScriptSupportEvent:registerEvent([=[Player.InputContent]=], admin_state)
ScriptSupportEvent:registerEvent([=[Player.Revive]=], Player_Revive)
--ScriptSupportEvent:registerEvent([=[Game.Start]=], AnyPlayer_EnterGame)
--ScriptSupportEvent:registerEvent([=[Game.Run]=], mainPlayer_EnterGame)
--ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], other_player_entergame)
ScriptSupportEvent:registerEvent([=[Player.ClickBlock]=],begin_game)
ScriptSupportEvent:registerEvent([=[Player.ClickBlock]=],any_enter_game)

--暂时放弃的代码
--ScriptSupportEvent:registerEvent([=[Game.AnyPlayer.EnterGame]=], all_equip)
--ScriptSupportEvent:registerEvent([=[Player.MoveOneBlockSize]=], Player_MoveStep)
--ScriptSupportEvent:registerEvent([=[Player.Init]=], Player_Inited)
--ScriptSupportEvent:registerEvent([=[Player.JoinTeam]=], Player_JoinTeam)


